<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
// use App\Notifications\InvoicePaid;
use App\Article; 
use App\Category;
use App\Paper;
use App\User;
use App\Notification;


class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // if ($request->user()->id != null){
        //     $user = User::find($request->user()->id); 
        //     $notifications = $notifiModel
        //     ->get(['id', 'read_at', 'data', 'created_at']); 
        //     var_dump($notifications);
        // }else{
           
        // }
        $notifications = Notification::all();
        $categories = Category::orderBy('page_num', 'desc')->paginate(8);
        $papers = Paper::where('result', 1)->orderBy('created_at', 'desc')->offset(1)->limit(4)->get();
        $fpaper = Paper::where('result', 1)->orderBy('created_at', 'desc')->first();
        if ($fpaper == ''){
            $fpaper = null;
        }
        // if( $begin = ''){
        //     $begin = 0;
        // }
        // if( $limit = ''){
        //     $limit = 0;
        // }
        // $articles = Article::with('hasManyUsers')->orderBy('created_at', 'desc')->offset($begin)->limit($num)->get();
        $articles = Article::with('hasManyUsers')->orderBy('created_at', 'desc')->paginate(6);
        return view('home', ['articles'=>$articles, 'categories'=>$categories, 'papers'=>$papers, 'fpaper'=>$fpaper]);
    }

    public function globalNotification(Request $request) {
        $user_id = $request->user()->id;
        $user = User::find($user_id);
        $no_user_id = $user->no_id;
        $notifications = Notification::where('to_user_id', 'like', '%'.$no_user_id.'%')
        ->where('read_user_id', 'not like', '%'.$no_user_id.'%')
        ->orderBy('created_at', 'desc')
        ->get();

        return response()->json($notifications, 200);
    }

    public function lazyIndex(Request $request){
        $offset = $request->input('offset');
        $limit = 6;
        // var_dump($offset);
        $articles = Article::with('hasManyUsers')->orderBy('created_at', 'desc')->offset($offset)->limit($limit)->get();
        return response()->json($articles, 200);
    }
}
